import subprocess
import os


class SrecordTool(object):
    def __init__(self):
        # 打包使用路径
        self.tool_path = "srec_cat.exe"
        # 直接运行调试使用路径
        # self.tool_path = "./srecord/bin/srec_cat.exe"
        self.base_addr = 0
        self.end_addr = 0
        self.src_hex = ""
        self.dist_bin = ""
        self.size = 0
        self.head = 0

    def get_hex_start_addr(self, filepath):
        # 获取hex文件存储的起始地址
        with open(filepath, "r") as f:
            line1 = f.readline()
            line2 = f.readline()

        if line1[7:9] == '04':
            print("识别到起始地址")
            self.base_addr = int('0x' + str(line1[9:13]) + str(line2[3:7]), 16)
            print(hex(self.base_addr))
            return True
        else:
            return False

    def get_bin_length(self):
        # 将原始hex文件转换为bin文件，输出到最终文件位置
        subprocess.run(
            [self.tool_path, self.src_hex, "-intel", "-offset", ("-" + str(hex(self.base_addr))), "-o", self.dist_bin,
             "-binary"])
        print("原始hex转bin......")
        # 获取原始bin文件长度
        self.size = os.path.getsize(self.dist_bin)
        self.end_addr = self.base_addr + self.size

    def hex_add_crc(self, checked):
        # 根据原始hex文件生成CRC32校验信息到midhex.hex文件
        if checked:
            subprocess.run(
                [self.tool_path, self.src_hex, "-intel", "-crop", str(hex(self.base_addr)), str(hex(self.end_addr)),
                 "-crc32-l-e", str(hex(self.end_addr)), "-o", "midhex.hex", "-intel"])
            print("生成CRC32校验信息......")
        else:
            subprocess.run(
                [self.tool_path, self.src_hex, "-intel", "-o", "midhex.hex", "-intel"])

    def hex2bin(self, checked):
        # 将生成的带crc32的hex文件转换成bin文件

        # 将界面的头部信息，生成一个二进制bin文件
        bin_data = self.head.to_bytes(4, 'little') + self.size.to_bytes(4, "little") + self.base_addr.to_bytes(4,
                                                                                                               "little")
        # bin_data = self.head.to_bytes(4, 'little') + self.size.to_bytes(4, "little")
        # 使用with open打开文件，文件在代码块结束时会自动关闭，无需手动关闭
        with open("head.bin", "wb") as bin_file:
            bin_file.write(bin_data)
        if checked:
            print("生成头部信息......")
        else:
            pass

        # 将带crc32信息的hex文件生成二进制bin文件
        subprocess.run(
            [self.tool_path, "midhex.hex", "-intel", "-offset", ("-" + str(hex(self.base_addr))), "-o",
             self.dist_bin,
             "-binary"])

        with open("head.bin", "rb") as file1:
            data1 = file1.read()

        with open(self.dist_bin, "rb") as file2:
            data2 = file2.read()

        if checked:
            # 合并头部信息和固件
            merged_data = data1 + data2
        else:
            merged_data = data2

        # 写入文件
        with open(self.dist_bin, "wb") as output_file:
            output_file.write(merged_data)
        print("生成固件......")

        # 删除中间文件
        print("删除过程文件......")
        os.remove("head.bin")
        os.remove("midhex.hex")

        
